package com.why.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.why.dao.OrderDetailMapper;
import com.why.dao.OrderMapper;
import com.why.pojo.Order;
import com.why.pojo.OrderDetail;
import com.why.pojo.Product;
import com.why.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;
    //新增订单并清空购物车
    @Override
    public boolean addOrder(Order order, List<Product> products) {
        int orderResult = orderMapper.insertSelective(order);
        int carResult = 0;
        for (Product product:products){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderid(order.getId());
            orderDetail.setProductid(Integer.parseInt(product.getId()));
            orderDetail.setQuantity(product.getCarcount());
            orderDetail.setCost(product.getPrice());
            carResult+= orderDetailMapper.insertSelective(orderDetail);
        }
        if (orderResult==1&&carResult==products.size()){
            return true;
        }
        return false;
    }

    @Override
    public PageInfo<Order> selectOrderByUserId(Integer id,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orders = orderMapper.selectOrderByUserId(id);
        PageInfo<Order> pageInfo = new PageInfo<>(orders);
        return pageInfo;
    }

    @Override
    public boolean cancelOrderById(Integer id) {
        if (orderMapper.cancelOrderById(id)==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteOrderById(Integer id) {
        if (orderMapper.deleteByPrimaryKey(id)==1){
            return true;
        }
        return false;
    }

    @Override
    public Order selectByPrimaryKey(Integer id) {
        return orderMapper.selectByPrimaryKey(id);
    }


}
